package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.BspsInspectRegisterInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsInspectTaskDetailMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsInspectRegisterInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsInspectTaskDetailMapperImpl;
import cc.rengu.igas.bsps.common.entity.InspectRegisterInfo;
import cc.rengu.igas.bsps.common.entity.InspectTaskDetail;
import cc.rengu.igas.bsps.common.enums.InspectStatusEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.bean.InspectImageInfoBean;
import cc.rengu.igas.bsps.facade.request.MchntSelfInspectRequest;
import cc.rengu.igas.bsps.facade.response.MchntSelfInspectResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import cc.rengu.utility.log.MessageFormatter;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020/04/05
 */
public class MchntSelfInspectService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntSelfInspectRequest mchntSelfInspectRequest = new MchntSelfInspectRequest();
        ConvertUtil.convertOutput(mchntSelfInspectRequest);
        return mchntSelfInspectRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        MchntSelfInspectRequest mchntSelfInspectRequest = (MchntSelfInspectRequest) request;
        MchntSelfInspectResponse mchntSelfInspectResponse = new MchntSelfInspectResponse();
        /*根据请求报文参数信息：法人行号，用户标识，商户号，巡检任务号，巡检影像信息*/
        String instId = mchntSelfInspectRequest.getHeader().getInstId();
        String userId = mchntSelfInspectRequest.getUserId();
        String mchntNo = mchntSelfInspectRequest.getMchntNo();
        String inspectTaskNo = mchntSelfInspectRequest.getInspectTaskNo();
        List<InspectImageInfoBean> inspectImageInfoList = mchntSelfInspectRequest.getInspectImageInfoList();
        /*校验自助巡检影像信息必填*/
        boolean imageListFlag = checkImageInfoVlae(inspectImageInfoList);
        /*判断请求信息中必填合法性*/
        if (StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(inspectTaskNo) || imageListFlag) {
            rglog.error("请求参数校验必填字段失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*1-登记自助巡检图片信息 2-更新商户巡检任务详情信息*/
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        int iReturnCode;
        /*1-登记自助巡检图片*/
        BspsInspectRegisterInfoMapper bspsInspectRegisterInfoMapper = new BspsInspectRegisterInfoMapperImpl();
        for (InspectImageInfoBean inspectImageInfo : inspectImageInfoList) {
            InspectRegisterInfo inspectRegisterInfo = bspsInspectRegisterInfoMapper.selectInspectRegisterInfoByPrimaryKey(instId, inspectTaskNo, mchntNo, inspectImageInfo.getCollectId());
            if (null == inspectRegisterInfo) {
                inspectRegisterInfo = new InspectRegisterInfo();
                /*法人行号赋值*/
                inspectRegisterInfo.setInstId(instId);
                /*巡检任务编号赋值*/
                inspectRegisterInfo.setInspectTaskNo(inspectTaskNo);
                /*商户号赋值*/
                inspectRegisterInfo.setMchntNo(mchntNo);
                /*采集信息标识:*/
                inspectRegisterInfo.setCollectId(inspectImageInfo.getCollectId());
                /*采集信息类型赋值*/
                inspectRegisterInfo.setCollectType(inspectImageInfo.getCollectType());
                /*采集信息描述*/
                inspectRegisterInfo.setCollectDesc(inspectImageInfo.getCollectDesc());
                /*采集信息赋值*/
                if ("2".equals(inspectImageInfo.getCollectType())) {
                    inspectRegisterInfo.setCollectValue(new String(Base64.decodeBase64(inspectImageInfo.getCollectValue())));
                } else {
                    inspectRegisterInfo.setCollectValue(inspectImageInfo.getCollectValue());
                }
                /*采集信息经度赋值*/
                inspectRegisterInfo.setCollectImageLng(inspectImageInfo.getCollectImageLng());
                /*采集信息纬度赋值*/
                inspectRegisterInfo.setCollectImageLat(inspectImageInfo.getCollectImageLat());
                /*记录状态：默认正式*/
                inspectRegisterInfo.setRecordStatus("Y");
                /*创建人信息赋值*/
                inspectRegisterInfo.setOprId(userId);
                /*创建时间赋值*/
                inspectRegisterInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                /*非业务主键赋值*/
                inspectRegisterInfo.setId(RandomUtil.getUUID());

                iReturnCode = bspsInspectRegisterInfoMapper.insertInspectRegisterInfo(inspectRegisterInfo);
                if (0 != iReturnCode) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("更新商户自助巡检图片信息失败,iReturnCode:<{}>,信息类型:<{}>,采集ID:<{}>", iReturnCode, inspectImageInfo.getCollectType(), inspectImageInfo.getCollectId());
                    throw new BizException(RespCodeEnum.INSERT_INSPECT_TASK_REGISTER_ERROR.getRespCode(), RespCodeEnum.INSERT_INSPECT_TASK_REGISTER_ERROR.getRespDesc());
                }
            } else {
                /*采集信息描述*/
                inspectRegisterInfo.setCollectDesc(inspectImageInfo.getCollectDesc());
                /*采集信息赋值*/
                if ("2".equals(inspectImageInfo.getCollectType())) {
                    inspectRegisterInfo.setCollectValue(new String(Base64.decodeBase64(inspectImageInfo.getCollectValue())));
                } else {
                    inspectRegisterInfo.setCollectValue(inspectImageInfo.getCollectValue());
                }
                /*采集信息经度赋值*/
                inspectRegisterInfo.setCollectImageLng(inspectImageInfo.getCollectImageLng());
                /*采集信息纬度赋值*/
                inspectRegisterInfo.setCollectImageLat(inspectImageInfo.getCollectImageLat());
                /*记录状态：默认正式*/
                inspectRegisterInfo.setRecordStatus("Y");
                /*创建人信息赋值*/
                inspectRegisterInfo.setOprId(userId);
                /*创建时间赋值*/
                inspectRegisterInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                iReturnCode = bspsInspectRegisterInfoMapper.updateInspectRegisterInfoById(inspectRegisterInfo);
                if (0 != iReturnCode) {
                    dbsUtil.dbsEndTransaction(false);
                    rglog.error("更新商户自助巡检图片信息失败,iReturnCode:<{}>,信息类型:<{}>,采集ID:<{}>", iReturnCode, inspectImageInfo.getCollectType(), inspectImageInfo.getCollectId());
                    throw new BizException(RespCodeEnum.INSERT_INSPECT_TASK_REGISTER_ERROR.getRespCode(), RespCodeEnum.INSERT_INSPECT_TASK_REGISTER_ERROR.getRespDesc());
                }
            }
        }
        /*2-更新商户巡检任务详情信息*/
        BspsInspectTaskDetailMapper bspsInspectTaskDetailMapper = new BspsInspectTaskDetailMapperImpl();
        InspectTaskDetail inspectTaskDetail = new InspectTaskDetail();
        /*法人行号赋值*/
        inspectTaskDetail.setInstId(instId);
        /*商户号赋值*/
        inspectTaskDetail.setMchntNo(mchntNo);
        /*巡检任务编号赋值*/
        inspectTaskDetail.setInspectTaskNo(inspectTaskNo);
        /*线上巡检任务完成状态赋值*/
        inspectTaskDetail.setInspectStatus(InspectStatusEnum.UNCHECK_STATUS.getStatusCode());
        /*巡检时间赋值*/
        inspectTaskDetail.setInspectTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        /*最后操作人赋值*/
        inspectTaskDetail.setLastOprId(userId);
        /*最后操作时间赋值*/
        inspectTaskDetail.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        iReturnCode = bspsInspectTaskDetailMapper.updateBspsInspectTaskDetailByMchntNoAndTaskNo(inspectTaskDetail);
        if (0 != iReturnCode) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("更新商户巡检任务信息失败,iReturnCode:<{}>,mchntNo:<{},inspectTaskNo:<{}>", iReturnCode, mchntNo, inspectTaskNo);
            throw new BizException(RespCodeEnum.UPDATE_INSPECT_TASK_DETAIL_ERROR.getRespCode(), RespCodeEnum.UPDATE_INSPECT_TASK_DETAIL_ERROR.getRespDesc());
        }
        dbsUtil.dbsEndTransaction(true);
        /* 拼装响应结果 */
        BizResponse<MchntSelfInspectResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(mchntSelfInspectResponse);
        return bizResponse;
    }

    /**
     * 校验自助巡检影像资料信息必填字段
     * inspectImageInfoList 自助巡检资料信息列表
     * return 必填信息是否为空标识
     */
    private boolean checkImageInfoVlae(List<InspectImageInfoBean> inspectImageInfoList) {
        boolean imageListFlag = false;
        Object[] argArray = new Object[]{};
        try {
            if (!CollectionUtils.isEmpty(inspectImageInfoList)) {
                for (InspectImageInfoBean inspectImageInfo : inspectImageInfoList) {
                    String collectDesc = inspectImageInfo.getCollectDesc();
                    if (StringUtil.isEmptyOrNull(collectDesc)) {
                        collectDesc = "巡检影像信息";
                    }
                    argArray = new Object[]{collectDesc};
                    String colletValueType = inspectImageInfo.getCollectType();
                    if (StringUtil.isEmptyOrNull(colletValueType)) {
                        imageListFlag = true;
                        break;
                    }
                    /*影像信息属性名称，属性首字母，获取属性方法，属性值*/
                    String fieldName;
                    String firstLetter;
                    String getterField;
                    String fieldValue;
                    Method method;
                    Field[] fields = inspectImageInfo.getClass().getDeclaredFields();
                    for (Field imageFiled : fields) {
                        fieldName = imageFiled.getName();
                        //非图片时不校验经纬度、图片序号信息
                        if (!"2".equals(colletValueType) && ("collectImageLng".equals(fieldName) || "collectImageLat".equals(fieldName) || "inspectImageIndex".equals(fieldName))) {
                            continue;
                        }
                        firstLetter = fieldName.substring(0, 1).toUpperCase();
                        getterField = "get" + firstLetter + fieldName.substring(1);
                        method = inspectImageInfo.getClass().getMethod(getterField);
                        fieldValue = method.invoke(inspectImageInfo).toString();
                        if (StringUtil.isEmptyOrNull(fieldValue)) {
                            rglog.info("影像信息必填字段校验失败！" + fieldName);
                            imageListFlag = true;
                            break;
                        }
                    }
                    if (imageListFlag) {
                        break;
                    }
                }
            } else {
                argArray = new Object[]{"巡检影像信息"};
                imageListFlag = true;
            }
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("影像信息必填字段校验失败！");
            String message = MessageFormatter.arrayFormat(RespCodeEnum.COLLECT_VALUE_NOT_NULL_ERROR.getRespDesc(), argArray).getMessage();
            throw new BizException(RespCodeEnum.COLLECT_VALUE_NOT_NULL_ERROR.getRespCode(), message);
        }
        if (imageListFlag) {
            String message = MessageFormatter.arrayFormat(RespCodeEnum.COLLECT_VALUE_NOT_NULL_ERROR.getRespDesc(), argArray).getMessage();
            rglog.error(message);
            throw new BizException(RespCodeEnum.COLLECT_VALUE_NOT_NULL_ERROR.getRespCode(), message);
        }
        return false;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntSelfInspectResponse mchntSelfInspectResponse = (MchntSelfInspectResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntSelfInspectResponse);
    }
}
